//封装mockjs  使用mockadapter来模拟前台请求
import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { LoginUsers, Users, push } from "./data/user";

export default {
  // mockjs 的 bootStrap
  bootstrap() {
    let mock = new MockAdapter(axios);
    let _users = Users;

    // 测试
    mock.onGet("/success").reply(200, {
      msg: "请求成功"
    });

    // 登录 当为post方式时 参数config.data保存了前台传过来的参数， get时config.params 保存了前台参数
    mock.onPost("/login").reply(config => {
      let { username, password } = JSON.parse(config.data);
      //Promise 异步编程的一种方案，类似回调函数，一般成功执行resolve,失败执行reject
      return new Promise((resolve, reject) => {
        let user = null;
        setTimeout(() => {
          let hasUser = LoginUsers.some(u => {
            if (u.username === username && u.password === password) {
              user = JSON.parse(JSON.stringify(u));
              user.password = undefined;
              return true;
            }
          });

          if (hasUser) {
            resolve([200, { code: 200, msg: "请求成功", user }]);
          } else {
            reject([200, { code: 500, msg: "账号或密码错误" }]);
          }
        }, 1000);
      });
    });

    // 用户列表
    mock.onGet("/user/list").reply(config => {
      let { name } = config.params;
      let mockUsers = _users.filter(user => {
        if (name && user.indexOf(name) === -1) return false;
        return true;
      });
      return new Promise(resolve => {
        setTimeout(() => {
          resolve([
            200,
            {
              users: mockUsers
            }
          ]);
        }, 1000);
      });
    });
    // 用户列表分页
    mock.onGet("/user/listpage").reply(config => {
      // 获取前台参数
      let { page, name } = config.params;
      // filter第一个参数必须为函数且不能省略 user参数为当前项
      let mockUsers = _users.filter(user => {
        //用于模糊查询，如果字符在名字中不存在就过滤掉
        if (name && user.name.indexOf(name) === -1) return false;
        return true;
      });
      let total = mockUsers.length;
      // 使用filter进行简单的分页
      mockUsers = mockUsers.filter(
        // u 为当前项 index 为当前项的索引值
        (u, index) => index < 10 * page && index >= 10 * (page - 1)
      );
      // 进行异步操作 resolve 成功时调用，reject失败时调用
      return new Promise(resolve => {
        // resolve([200,{total: total, users: mockUsers}]);
        setTimeout(() => {
          resolve([
            200,
            {
              total: total,
              users: mockUsers
            }
          ]);
        }, 1000);
      });
    });

    // 添加数据
    mock.onGet("/user/add").reply(config => {
      let { id, name, addr, age, birth, sex } = config.params;
      _users.push({
        id: id,
        name: name,
        addr: addr,
        age: age,
        birth: birth,
        sex: sex
      });
      return new Promise(resolve => {
        setTimeout(() => {
          resolve([
            200,
            {
              code: 200,
              msg: "新增成功"
            }
          ]);
        }, 500);
      });
    });

    // 编辑
    mock.onGet("/user/edit").reply(config => {
      console.log(config);
      let { id, name, addr, age, birth, sex } = config.params;
      //  map():返回一个新的Array，每个元素为调用func的结果
      // filter():返回一个符合func条件的元素数组
      // some():返回一个boolean，判断是否有元素是否符合func条件
      // every():返回一个boolean，判断每个元素是否符合func条件
      // forEach():没有返回值，只是针对每个元素调用func
      // 如果id 不存在进行添加，否则就修改
      if (id == null || id == "" || id == 0) {
        console.log("开始添加");
      } else {
        _users.some(u => {
          if (u.id === id) {
            u.name = name;
            u.addr = addr;
            u.age = age;
            u.bitrh = birth;
            u.sex = sex;
            return true;
          }
        });
      }
      return new Promise(resolve => {
        setTimeout(() => {
          resolve([
            200,
            {
              code: 200,
              msg: "数据保存成功！"
            }
          ]);
        }, 500);
      });
    });

    // 删除
    mock.onGet("user/remove").reply(config => {
      let { id } = config.params;
      // 遍历_user 找出与该id不同的项 即删除
      _users = _users.filter(u => u.id !== id);
      return new Promise(resolve => {
        setTimeout(() => {
          resolve([
            200,
            {
              code: 200,
              msg: "删除成功！"
            }
          ]);
        }, 500);
      });
    });
  }
};
